<template>
  <div>
    <div class="search">
      <el-input placeholder="请输入姓名查询" style="width: 200px" v-model="creatorName"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="operation" v-if="user.role !== 'GENERAL_MANAGER'">
      <el-button type="primary" plain @click="handleAdd" >新增</el-button>
    </div>

    <div class="table">
      <el-table :data="tableData" stripe  @selection-change="handleSelectionChange">
        <el-table-column type="index" :index="hIndex" label="序号" width="70"></el-table-column>
        <el-table-column prop="leaveType" label="请假类型" show-overflow-tooltip></el-table-column>
        <el-table-column prop="creatorName" label="申请人"></el-table-column>
        <el-table-column prop="beginTime" label="开始时间"></el-table-column>
        <el-table-column prop="endTime" label="结束时间"></el-table-column>
        <el-table-column prop="day" label="天数"></el-table-column>
        <el-table-column prop="examineName" label="处理人"></el-table-column>
        <el-table-column prop="comment" label="处理意见"></el-table-column>
        <el-table-column prop="status" label="审批结果"></el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <el-button plain type="primary" @click="handleEdit(scope.row)" size="mini" v-if="user.id===scope.row.examineId&&scope.row.status!=='已批准'">审批</el-button>
            <el-button plain type="primary" size="mini" @click=handleEdit2(scope.row) v-if="user.id===scope.row.createId&&scope.row.status!=='已批准'">编辑</el-button>
            <el-button plain type="danger" size="mini" @click=del(scope.row.id) v-if="user.id===scope.row.createId&&scope.row.status!=='已批准'">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>


    <el-dialog title="新增请假申请" :visible.sync="addVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef"><el-form-item prop="title" label="请假类型">
        <el-select v-model="form.leaveType" placeholder="请选择">
          <el-option label="事假" value="事假" prop="leaveType"></el-option>
          <el-option label="病假" value="病假" prop="leaveType"></el-option>
        </el-select>
      </el-form-item>
        <el-form-item prop="beginTime" label="开始时间">
          <el-date-picker v-model="form.beginTime" type="date" format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item prop="endTime" label="结束时间">
          <el-date-picker v-model="form.endTime" type="date" format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item prop="leaveDetails" label="具体内容">
          <el-input type="textarea" :rows="5" v-model="form.leaveDetails" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="审核" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form label-width="100px" style="padding-right: 50px" :model="form"  ref="formRef">
        <el-form-item prop="status" label="审核结果">
          <el-select v-model="form.status" style="width: 250px;margin-left: 10px" placeholder="请选择结果">
            <el-option key="审核通过" value="已批准" label="审核通过"></el-option>
            <el-option key="审核不通过" value="未批准" label="审核不通过"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="comment" label="处理意见">
          <el-input type="textarea" :rows="5" v-model="form.comment" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="leaveDetails" label="详细缘由">
          <el-input type="textarea" :rows="5" :value="form.leaveDetails" autocomplete="off" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import moment from 'moment';
export default {

  name: "Leave",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      title: null,
      fromVisible: false,
      dialogVisible: false,
      addVisible:false,
      creatorName: null,
      form: {
      },
      pickerOptions: {
        // 可以根据需求设置时间选择器的选项
      },
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        leaveType: [
          {required: true, message: '请选择请假类型', trigger: 'blur'},
        ],
        leaveDetails: [
          {required: true, message: '请输入具体缘由', trigger: 'blur'},
        ],
        beginTime: [
          {required: true, message: '请选择开始时间', trigger: 'blur'},
        ],
        endTime: [
          {required: true, message: '请选择结束时间', trigger: 'blur'},
        ]
      },
      ids: []
    }
  },
  created() {
    this.load(1)
  },
  methods: {
    // 点击新增，打开新增请假模态框
    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.addVisible = true   // 打开弹窗
    },
    // 点击审批按钮弹出审批模态框
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },
    // 点击编辑打开编辑模态框
    handleEdit2(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.addVisible = true   // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新

      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 格式化开始时间和结束时间
          this.form.beginTime = moment(this.form.beginTime).format('YYYY-MM-DD');
          this.form.endTime = moment(this.form.endTime).format('YYYY-MM-DD');
          this.$request({
            url: this.form.id ? '/leave/update' : '/leave/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.addVisible = false
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定取消申请吗？', '取消申请', {type: "warning"}).then(response => {
        this.$request.delete('/leave/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)   //  [1,2]
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/leave/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/leave/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          creatorName: this.creatorName,
        }
      }).then(res => {
        this.tableData = res.data?.list
        this.total = res.data?.total
      })
    },
    reset() {
      this.creatorName = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    // 当前页数 - 1 * 每页数据条数 + index + 1 （ index 是索引值，从0开始）
    hIndex(index) {
      return (this.pageNum - 1) * this.pageSize + index + 1;
    }
  },
  showDialog() {
    this.dialogVisible = true;
  },
  saveForm() {
    // 在保存表单数据时，你可以使用this.form.startTime和this.form.endTime来获取选择的时间值
    console.log('开始时间:', this.form.startTime);
    console.log('结束时间:', this.form.endTime);
    // 其他保存表单数据的逻辑
    // ...
    // 关闭弹窗
    this.dialogVisible = false;
  },
}
</script>

<style scoped>

</style>
